<?php

namespace Kangcg\Application\Validate\Rules;

use Kangcg\Application\Validate\Exception\RuleConfigureException;
use Kangcg\Application\Validate\Validator;

class Length implements RuleInterface
{
    use RuleTrait;

    public $max = null;
    public $min = null;

    protected function afterRun(&$value, string $field, array $input, Validator $validator)
    {
        if (strlen($value) > $this->max){
            return $validator->setError($this->getMessage($field, $this->max));
        }
    }

    public function extra($extra)
    {
        if(is_int($extra)){
            return [
                'min' => $extra,
            ];
        }elseif (is_array($extra)){
            if(isset($extra['max']) || isset($extra['min'])){
                return $extra;
            }

            if(isset($extra[0]) && isset($extra[1])){
                return [
                    'max' => $extra[0],
                    'min' => $extra[1],
                ];
            }
        }

        throw new RuleConfigureException("验证规则 Length 配置错误，期望【 length => 15 | length => [2, 15] | length => ['min' => 2, 'max' => 255]】!");
    }
}
